package com.idbk.chargestation.activity.user;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonUser;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.DateUtils;
import com.idbk.chargestation.util.GsonUtils;

import java.lang.ref.WeakReference;
import java.util.Date;

/**
 * 修改密码
 *
 * @author zhx
 */
public class ActivityResetPassword extends BaseActivity implements OnClickListener {

    private final static String TAG = ActivityResetPassword.class.getSimpleName();
    private Context mContext;
    private Button mBtnVcode;
    private EditText mEdtPassword, mEdtVcode;
    private String mPhoneNum, mOldPassword, mPassword, mVcode, mBindNum;
    public final static String KEY_EDIT_INDEX = "key_edit_index";
    private int mUserRole;
    private ImageView mImgPasswordStyle;
    private boolean mIsPasswordShowFlag = false;
    private static MyHandle mHandle;
    private static int mCount = 120;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_reset_password);

        mContext = this;

        setupView();
    }

    private void setupView() {
        setupToolBar2();//显示标题栏
        initWidgetView();
        initOnClickView();
    }

    private void initWidgetView() {
        mEdtVcode = (EditText) findViewById(R.id.edittext_vcode);
        mEdtPassword = (EditText) findViewById(R.id.edittext_password);
        mBtnVcode = (Button) findViewById(R.id.button_get_vcode);

        mImgPasswordStyle = (ImageView) findViewById(R.id.button_showpassword);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        mBtnVcode.setOnClickListener(this);
        mImgPasswordStyle.setOnClickListener(this);
        findViewById(R.id.button_submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_submit:
                resetPassword();
                break;
            case R.id.button_get_vcode:
                getVcode();
                break;
            case R.id.button_showpassword:
                changePwdStyle();
                break;
            default:
                break;
        }
    }

    //明文和暗文的转换
    private void changePwdStyle() {
        if (mIsPasswordShowFlag) {
            mIsPasswordShowFlag = false;
            mImgPasswordStyle.setImageResource(R.drawable.btn_login_password_visible);
            mEdtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

        } else {
            mIsPasswordShowFlag = true;
            mImgPasswordStyle.setImageResource(R.drawable.btn_login_password_hidden);
            mEdtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    private void getVcode() {
        if (checkPhoneNum()) {
            getCode();
        }
    }


    private boolean checkPhoneNum() {
        AppContext ac = AppContext.getInstance();
        mUserRole = ac.getUserRole();
        if (mUserRole ==  JsonUser.COMMON_USER) {
            mPhoneNum = ac.getLoginUserName();
        }else {
            mPhoneNum = getIntent().getStringExtra("userMobile");
        }
        if (mPhoneNum.equals("") || mPhoneNum.length() != 11) {
            Toast.makeText(ActivityResetPassword.this, R.string.tip_please_input_username, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void getCode() {
        showMyProgressDialog(true, false, "发送中...");
        String timestamp = DateUtils.dateToString(new Date());
        String sign = getSign(timestamp);
        mMainRequest = ChargeStationAPI.getUserBindSMS(mPhoneNum, timestamp, sign, mVcodeCallBall);
    }

    private String getSign(String timestamp) {
        String sign = "";
        try {
            AppContext ac = AppContext.getInstance();
            sign = ac.getSign(mPhoneNum, timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    private EHttpResponse mVcodeCallBall = new EHttpResponse() {
        @Override
        public void onEResponse(String response) {
            mMainProgressDialog.dismiss();
            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
            if (handleResponseStatus(result)) {
                changeVcodeButtonStyle();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {

            mMainProgressDialog.dismiss();
            Toast.makeText(mContext, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            dismissMyProgressDialog();
        }
    };

    private void changeVcodeButtonStyle() {
        mBtnVcode.setClickable(false);
        String time = "120秒后重发";
        mBtnVcode.setText(time);
        mBtnVcode.setBackgroundResource(R.drawable.bg_vcode_down);
        mCount = 120;
        mHandle = new MyHandle(ActivityResetPassword.this);
        mHandle.sendEmptyMessageDelayed(1, 1000);
        Toast.makeText(mContext, R.string.common_sms_success, Toast.LENGTH_SHORT).show();
    }

    private static class MyHandle extends Handler {
        WeakReference<ActivityResetPassword> mActivity;

        MyHandle(ActivityResetPassword activity) {
            mActivity = new WeakReference<ActivityResetPassword>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ActivityResetPassword theActivity = mActivity.get();
            if (theActivity == null)
                return;
            if (msg.what == 1) {
                mCount--;
                if (mCount < 1) {
                    theActivity.mBtnVcode.setClickable(true);
                    theActivity.mBtnVcode.setText(R.string.activity_register_getcheckCode);
                    theActivity.mBtnVcode.setBackgroundResource(R.drawable.bg_vcode_up);
                } else {
                    String time = mCount + "秒后重发";
                    theActivity.mBtnVcode.setText(time);
                    mHandle.sendEmptyMessageDelayed(1, 1000);
                }
            }
        }
    }

    private void resetPassword() {
        if (checkInput()) {
            changePassword();
        }
    }

    private boolean checkInput() {
        mPassword = mEdtPassword.getText().toString();
        mVcode = mEdtVcode.getText().toString();
        mOldPassword = AppContext.getInstance().getLoginPassword();
        if ( mPassword.length() != 0) {
            if ( mPassword.length() < 6 || mPassword.length() > 20 ) {
                Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_password), Toast.LENGTH_SHORT).show();
                mEdtPassword.setFocusable(true);
                return false;
            }
        }
        if (mVcode.equals("") || mVcode.length() != 6) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_checkcode), Toast.LENGTH_SHORT).show();
            mEdtVcode.setText("");
            mEdtVcode.setFocusable(true);
            return false;
        }
        return true;
    }

    private void changePassword() {
        showMyProgressDialog(true, true, "提交中...");
        mMainRequest = ChargeStationAPI.resetPassword(mOldPassword, mPassword, mPassword, mVcode, mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
            if (handleResponseStatus(result)) {
                Toast.makeText(mContext, R.string.common_edit_success, Toast.LENGTH_SHORT).show();
                AppContext.getInstance().setLoginPassword(mEdtPassword.getText().toString());
                finish();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error.getCause());
            Toast.makeText(mContext, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }
    };

}
